package com.up.api.js;

import com.oracle.truffle.js.scriptengine.GraalJSScriptEngine;
import org.graalvm.polyglot.proxy.ProxyObject;

import javax.script.Invocable;
import javax.script.ScriptEngineManager;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: liuchengjun
 * @title: JsRun
 * @projectName: 海联技术中台V2.0
 * @depart 软件事业部
 * @description:
 * @date: 2024/1/25/025 17:36 (星期四)
 * @since V2.0
 */
public class JsRun {
    private final String codeTemplate = "(function(input){\n" +
            "    console.log(input);\n" +
            "{%s}\n"+
            "    return output;\n" +
            "})";

    public static void main(String[] args) {
        JsRun jsRun = new JsRun();
        try {
            jsRun.method2();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public void method2() throws Exception {
        //https://www.graalvm.org/latest/reference-manual/js/JavaInteroperability/#enabling-java-interoperability
        //https://stackoverflow.com/questions/53831207/graalvm-java-complex-object-cant-be-parsed-like-javascript-object
        GraalJSScriptEngine engine = (GraalJSScriptEngine)new ScriptEngineManager().getEngineByName("graal.js");
        Map<String, Object> inputData = new HashMap<>();
        inputData.put("a",1);
        ProxyObject proxyObject = ProxyObject.fromMap(inputData);
        String code = "output = {\"hello\": input.a };";
        Object fn = engine.eval(String.format(codeTemplate, code));
        Invocable inv = (Invocable) engine;
        Object result = inv.invokeMethod(fn, "call", engine.getBindings(javax.script.ScriptContext.ENGINE_SCOPE), proxyObject);
    }
}
